#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import pwd
import shutil
import pathlib
from ...._util import Util, CopiedAndSymlinkedDir
from ...._game import GameBase, GameSpec, MatchContext
from ...._game_straits import GameStraitForWindows, GameStraitNeedConfigDir


class NeighboursFromHell(GameBase, GameStraitForWindows):

    def __init__(self, data_dir):
        GameBase.__init__(self, data_dir)

        self._addStrait(GameStraitNeedConfigDir())

        self._spec = GameSpec()
        if True:
            self._spec.windows_archs = [self.WindowsArch.WIN32]
            self._spec.windows_versions = [self.WindowsVersion.WINXP, "*"]

            self._spec.default_language = "en_US"
            self._spec.languages = [self._spec.default_language]

            # self._spec.resolutions = ["640x480", "800x600", "1024x768", "1280x1024", "1600x1200", "2048x1536"]
            self._spec.resolutions = ["640x480"]
            self._spec.can_fullscreen = True
            self._spec.can_windowed = False

    @property
    def spec(self):
        return self._spec

    @property
    def run_items(self):
        return ["main"]

    def get_title(self, lang):
        return "Neighbours from Hell"

    def _prepare(self, context):
        self._context = context
        try:
            self._targetGameDirObj = CopiedAndSymlinkedDir(os.path.join(self._context.drive_c_dirpath, "game"), [self._dataDir])
            self._targetGameDirObj.symlink("", recursive=True)
            self._targetGameDirObj.clear()

            self._cfgFile = _SettingsFile(self._targetGameDirObj.path)

            self._profileRepo = _ProfileRepository(self._context.drive_c_dirpath, self._context.config_dirpath)
            # self._profileRepo.restore_current()
        except BaseException:
            self._cleanup(on_error=True)
            raise

    @MatchContext.edit_or_run
    def get_language(self):
        return self._spec.default_language

    @MatchContext.edit_or_run
    def set_language(self, language):
        assert language == self._spec.default_language

    @MatchContext.edit
    def list_backup_profiles(self):
        return self._profileRepo.list_backups()

    @MatchContext.edit
    def save_backup_profile(self, name):
        assert name is not None
        self._profileRepo.backup_current(name)

    @MatchContext.edit
    def remove_backup_profile(self, name):
        assert name is not None
        self._profileRepo.remove_backup(name)

    @MatchContext.edit
    def use_backup_profile(self, name):
        assert name is not None
        self._profileRepo.restore_current(name)

    @MatchContext.edit
    def use_perfect_profile(self):
        self._profileRepo.use_perfect_profile_as_current()

    @MatchContext.edit
    def reset_profile(self):
        self._profileRepo.remove_current()

    @MatchContext.run
    def apply_resolution(self, resolution):
        assert resolution in self._spec.resolutions

    @MatchContext.run
    def apply_fullscreen_or_windowed(self, fullscreen_or_windowed):
        self._cfgFile.fullscreen = fullscreen_or_windowed

    def _commit(self):
        self._cfgFile.save()

    def _getRunInfo(self, item):
        assert not self._context.edit_or_run
        assert item == Util.listGetOnlyItem(self.run_items)

        return self.RunInfo("C:\\game\\bin\\game.exe", cwd="C:\\game\\bin")

    def _cleanup(self, on_error=False):
        if not on_error:
            self._profileRepo.backup_current()

        if hasattr(self, "_targetGameDirObj"):
            if not on_error:
                pass
            del self._targetGameDirObj
        if hasattr(self, "_context"):
            del self._context


class _SettingsFile:

    def __init__(self, drive_c_dirpath):
        username = pwd.getpwuid(os.geteuid()).pw_name

        self._path = os.path.join(drive_c_dirpath, "users", username, "Documents", "JoWooD", "NFH1", "gameoptions.xml")

        # variables
        self._fullscreen = True        # default value
        self._autoScroll = False       # default value
        self._timeLimit = True         # default value

        if os.path.exists(self._path):
            buf = pathlib.Path(self._path).read_text()

        self._modified = False

    @property
    def fullscreen(self, value):
        if self._fullscreen == bool(value):
            return
        self._fullscreen = bool(value)
        self._modified = True

    @fullscreen.setter
    def fullscreen(self, value):
        return self._fullscreen

    @property
    def autoscroll(self, value):
        if self._autoscroll == bool(value):
            return
        self._autoscroll = bool(value)
        self._modified = True

    @autoscroll.setter
    def autoscroll(self, value):
        return self._autoscroll

    @property
    def timelimit(self, value):
        if self._timelimit == bool(value):
            return
        self._timelimit = bool(value)
        self._modified = True

    @timelimit.setter
    def timelimit(self, value):
        return self._timelimit

    def save(self):
        if not self._modified:
            return

        # generate file content
        buf = '<?xml version="1.0"?>\n'
        buf += '\n'
        buf += '<gameoptions>\n'
        buf += '\t<ingame autoscroll="%s" timelimit="%s"/>\n' % (self._bool2str(self._autoScroll), self._bool2str(self._timeLimit))
        buf += '\t<screen fullscreen="%s" showfps="false" bitdepth="16" backbuffer="0" coloredcursors="true"/>\n' % (self._bool2str(self._fullscreen))
        buf += '\t<sfx soundquality="1" mastermute="false" mastervolume="96" musicmute="false" musicvolume="64" dynamicmusic="false" logsound="false"/>\n'
        buf += '\t<system loggamelogic="false" logpaintserver="false" forcepaintserver="0" advancedpainter="0"/>\n'
        buf += '\t<capture fps="0"/>\n'
        buf += '</gameoptions>\n'

        # write file
        os.makedirs(os.path.dirname(self._path), exist_ok=True)
        with open(self._path, "w", encoding="utf-16") as f:
            f.write(buf.replace("\n", "\r\n"))

        self._modified = False

    @staticmethod
    def _bool2str(value):
        return "true" if value else "false"


class _ProfileRepository:

    def __init__(self, drive_c_dirpath, backup_dir):
        username = pwd.getpwuid(os.geteuid()).pw_name

        self._tPath = os.path.join(drive_c_dirpath, "users", username, "Documents", "JoWooD", "NFH1", "userdata.ngh")
        self._backupDir = backup_dir

    def list_backups(self):
        ret = []
        for fn in os.listdir(self._backupDir):
            if fn == "userdata.ngh":
                continue
            if not fn.endswith(".ngh"):
                continue
            ret.append(fn)
        return ret

    def remove_current(self):
        Util.forceDelete(os.path.dirname(os.path.dirname(self._tPath)))
        Util.forceDelete(os.path.join(self._backupDir, "userdata.ngh"))

    def remove_backup(self, name):
        assert name is not None
        Util.forceDelete(os.path.join(self._backupDir, self._name2fn(name)))

    def backup_current(self, name=None):
        bakFile = os.path.join(self._backupDir, self._name2fn(name))
        if os.path.exists(self._tPath):
            shutil.copy(self._tPath, bakFile)
        else:
            Util.forceDelete(bakFile)

    def restore_current(self, name=None):
        bakFile = os.path.join(self._backupDir, self._name2fn(name))
        if os.path.exists(bakFile):
            os.makedirs(os.path.dirname(self._tPath), exist_ok=True)
            shutil.copy(bakFile, self._tPath)
        else:
            Util.forceDelete(os.path.dirname(os.path.dirname(self._tPath)))

    def use_perfect_profile_as_current(self):
        selfDir = os.path.dirname(os.path.realpath(__file__))
        os.makedirs(os.path.dirname(self._tPath), exist_ok=True)
        shutil.copy(os.path.join(selfDir, "userdata.ngh"), self._tPath)

    @staticmethod
    def _name2fn(name):
        if name is None:
            return "userdata.ngh"
        else:
            if name == "userdata":
                raise ValueError("invalid profile name")
            return name + ".ngh"
